import Tips from '@/utils/tips'
import {
  cryptoToken,
  authorize
} from '@/utils/auth'

export const baseUrl = process.env.HOST

/**
 * 基于wx的小程序网络请求封装类
 * @author lixiao
 */
export default class MPRequest {
  /**
   * 网络请求的前置逻辑，获取token
   */
  static async beforeAction (url) {
    console.log('will load request uri:', url)
    let authToken = mpvue.getStorageSync('accessToken')
    if (authToken) {
      console.log('accessToken', authToken)
      return Promise.resolve(authToken)
    }
    console.log('没有auth token的情况')
    authToken = await authorize()
    return Promise.resolve(authToken)
  }

  static formatRequestUrl (uri) {
    uri = uri.replace(process.env.HOST, '')
    uri = uri.replace(/^(\s|\/)+|(\s|\/)+$/g, '')
    return process.env.HOST + '/' + uri
  }

  static getAccessToken (token) {
    return 'Bearer ' + cryptoToken(token)
  }

  static async request (method, url, data, header, loading = true, needTip = true) {
    const token = await this.beforeAction(url)
    if (loading) {
      Tips.navLoading()
    }
    let headOptions = Object.assign({
      'Content-Type': 'application/json',
      'Authorization': this.getAccessToken(token)
    }, header)

    // console.log('HeadOptions', headOptions)

    let reqURL = this.formatRequestUrl(url)
    return new Promise((resolve, reject) => {
      wx.request({
        url: reqURL,
        method: method || 'GET',
        data: data,
        header: headOptions,
        success: (res) => {
          console.log('response: ', res)
          const {statusCode, data} = res
          if (statusCode === 200) {
            resolve(data)
          } else if (statusCode === 401) {
            console.log('重新请求')
            authorize()
          } else if (statusCode === 402 || statusCode === 403) {
            console.log('需要用户登录')
            wx.switchTab({
              url: '/pages/user/main'
            })
            wx.showToast({
              title: '请先登录并激活当前账号',
              icon: 'none',
              duration: 2000
            })
          } else {
            let error = {}
            if (data.code) {
              error.statusCode = statusCode
              error.code = data.code
              error.errMsg = data.message
            } else {
              error.errMsg = data.error
            }
            console.log(error)
            if (needTip) {
              Tips.error(error.errMsg)
            }
            return reject(error)
          }
        },
        complete: () => {
          if (loading) {
            Tips.navLoaded()
          }
        },
        fail: (errObj) => {
          console.log(errObj)
          let error = {}
          error.statusCode = 500
          error.code = 500
          error.errMsg = errObj.errMsg
          if (needTip) {
            Tips.error(error.errMsg)
          }
          return reject(error)
        }
      })
    })
  }

  static async upload (url, file, type = 'image', loading = true, needTip = true) {
    const token = await this.beforeAction()
    if (loading) {
      Tips.navLoading()
    }
    let headOptions = Object.assign({
      'Authorization': this.getAccessToken(token)
    })

    console.log('HeadOptions', headOptions)

    let reqURL = this.formatRequestUrl(url)
    return new Promise((resolve, reject) => {
      wx.uploadFile({
        url: reqURL, // 仅为示例，非真实的接口地址
        filePath: file.url,
        name: 'streamFile',
        header: headOptions,
        formData: {
          format: type
        },
        success: (res) => {
          const {statusCode, data} = res
          console.log('statusCode: ', statusCode)
          console.log('data: ', data)
          console.log('uploaded: ', res)
          const resdata = JSON.parse(data)
          console.log('res>>>>>>', resdata)
          if (statusCode === 200) {
            resolve(resdata)
          } else if (statusCode === 401) {
            console.log('重新请求')
            authorize()
          } else {
            let error = {}
            if (resdata.code) {
              error.statusCode = statusCode
              error.code = resdata.code
              error.errMsg = resdata.message
            } else {
              error.errMsg = resdata.error
            }
            console.log(error)
            if (needTip) {
              Tips.error(error.errMsg)
            }
            return reject(error)
          }
        },
        complete: () => {
          if (loading) {
            Tips.navLoaded()
          }
        },
        fail: (errObj) => {
          let error = {}
          error.statusCode = 500
          error.code = 500
          error.errMsg = errObj.errMsg
          if (needTip) {
            Tips.error(error.errMsg)
          }
          return reject(error)
        }
      })
    })
  }

  static get (url, data, loading = true) {
    console.log('Method get:', url)
    return this.request('GET', url, data, loading, true)
  }

  static post (url, data, loading = true) {
    console.log('Method post:', url)
    return this.request('POST', url, data, loading, true)
  }
}
